package com.hongfan.oauth.service.impl;

import com.hongfan.common.constants.Oauth2Const;
import com.hongfan.oauth.dto.Oauth2TokenDto;
import com.hongfan.oauth.service.AuthService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Service;
import org.springframework.web.HttpRequestMethodNotSupportedException;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zcs
 * @since 2023/10/16
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private TokenEndpoint tokenEndpoint;


    @Override
    public Oauth2TokenDto postAccessToken(String username, String password) {
        OAuth2AccessToken oAuth2AccessToken = getWebPwdAccessToken(username, password);
        if (oAuth2AccessToken == null) {
            return null;
        }
        return Oauth2TokenDto.builder()
                .accessToken(oAuth2AccessToken.getValue())
                .tokenType(oAuth2AccessToken.getTokenType())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .expires(oAuth2AccessToken.getExpiration()).build();
    }


    /**
     * 密码模式获取登录token
     *
     * @param userName 登录账号
     * @param password 登录密码
     * @return 授权信息
     */
    public OAuth2AccessToken getWebPwdAccessToken(String userName, String password) {
        try {
            Map<String, String> map = new HashMap<>(3);
            map.put("username", userName);
            map.put("password", password);
            map.put("grant_type", "password");
            final User clientUser = new User(Oauth2Const.CLIENT_ID, Oauth2Const.CLIENT_PASSWORD, new ArrayList<>());
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(clientUser, null, new ArrayList<>());
            return tokenEndpoint.postAccessToken(token, map).getBody();
        } catch (HttpRequestMethodNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }
}
